#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib

class zyb():
    def get_news(self):
        href_list = []
        title_list = []
        start_url ='http://l.zhangyoubao.com/news/'
        headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
        all_html = requests.get(start_url, headers=headers)
        all_html.encoding = 'utf-8'
        news_list = BeautifulSoup(all_html.text, 'html5lib').find('ul', class_='article-list').find_all('h2')
        for list in news_list:
            news = list.find('a')
            href = news['href']
            title = news.get_text().strip()
            href_list.append(href)
            title_list.append(title)
        print('get news ok')
        self.msg(href_list,title_list)
    def sendemail(self,massage):
        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))
        from_addr = '571766342@qq.com'
        password = 'ciklptyazjpvbfaa'
        # 输入收件人地址:
        to_addr = 'li_jagoo@163.com'
        # 输入SMTP服务器地址:
        smtp_server = 'smtp.qq.com'
        msg= MIMEText('<html><body><h1>掌游宝新闻</h1>' +
    massage+
    '</body></html>', 'html', 'utf-8')
        msg['From'] = _format_addr('掌游宝 <%s>' % from_addr)
        msg['To'] = _format_addr('管理员 <%s>' % to_addr)
        msg['Subject'] = Header('掌游宝新闻', 'utf-8').encode()
        server = smtplib.SMTP_SSL(smtp_server, 465)  # SMTP协议默认端口是25
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
        print('send email Success!')
    def msg(self,href,title):
        n=len(href)
        mail_context = ""
        for i in range(0, n):
            mail_context += "<p>"
            mail_context += "<span><a href=\""
            mail_context += href[i]
            mail_context += "\" target=_blank>"
            mail_context += title[i]
            mail_context += "</a></span>"
        mail_context += "</p>"
        self.sendemail(mail_context)
ZYB=zyb()
ZYB.get_news()
print('已发送掌游宝最近新闻到您的邮箱！')